<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import="com.google.gdata.client.authn.oauth.*" %>
<%@ page import="java.net.URL" %>


<%@ page import="com.google.gdata.data.*" %>
<%@ page import="com.google.gdata.data.acl.*" %>
<%@ page import="com.google.gdata.data.calendar.*" %>
<%@ page import="com.google.gdata.data.extensions.*" %>
<%@ page import="com.google.gdata.util.*" %>
<%@ page import="java.net.URL" %>
<%@ page import="com.google.gdata.client.calendar.*" %>
<%@ page import="java.util.*" %>
<%@ page import="com.soonzlab.server.AuthDataCenter" %>
<%@ page import="java.io.BufferedReader" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="com.google.gdata.client.*" %>
<%@ page import="java.text.DateFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String CONSUMER_KEY = AuthDataCenter.CONSUMER_KEY;
String CONSUMER_SECRET = AuthDataCenter.CONSUMER_SECRET;

//3 get OAuth
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);

GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthHelper.getOAuthParametersFromCallback(request.getQueryString(), oauthParameters);
out.println("<br>session key: " + session.getId());
String aSecretToken = (String)session.getAttribute("aSecretToken");
out.println("<br>aSecretToken: " + aSecretToken);
oauthParameters.setOAuthTokenSecret(aSecretToken);

//4 upgrade OAuth to long time
String accessToken = oauthHelper.getAccessToken(oauthParameters);

// You can also pull the OAuth token string from the oauthParameters:
// String accessToken = oauthParameters.getOAuthToken();
out.println("<br>OAuth Access Token: " + accessToken);

//String accessTokenSecret = oauthParameters.getOAuthTokenSecret();
//out.println("<br>OAuth Access Token's Secret: " + accessTokenSecret);



//oauthParameters.setOAuthToken(accessToken);
session.setAttribute("accessToken", accessToken);
session.setAttribute("aSecretToken", oauthParameters.getOAuthTokenSecret());

//calendar
CalendarService myService = new CalendarService("godshunfenger-exampleApp-2");
myService.setOAuthCredentials(oauthParameters,new OAuthHmacSha1Signer());

// Send the request and print the response
//URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
//URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
URL feedUrl =null; 
//CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
//CalendarEventFeed myFeed = myService.getFeed(feedUrl, CalendarEventFeed.class);
//out.println("Your calendars:");
//out.println("<br>");
//if (myFeed.getEntries().size() > 0) {
	  //CalendarEventEntry firstMatchEntry = (CalendarEventEntry)
	    //  myFeed.getEntries().get(0);
	  //String myEntryTitle = firstMatchEntry.getTitle().getPlainText();
	  //out.println(myEntryTitle);
	//}
//for (int i = 0; i < resultFeed.getEntries().size(); i++) {
  //CalendarEntry entry = resultFeed.getEntries().get(i);
  //out.println("<br>" + entry.getTitle().getPlainText());
//}

		//session.setAttribute("accessToken", accessToken);

		
		//calendar 
		
		// Send the request and print the response
		out.println("<br>");
		out.println("<br>");
		out.println("Retrieving all calendars");
		feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
		CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
		System.out.println("Your calendars:");
		System.out.println();
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
		  CalendarEntry entry = resultFeed.getEntries().get(i);
		  out.println("<br>");
		  out.println("\t" + entry.getTitle().getPlainText());
		}
		

/*
		out.println("<br>");
		out.println("<br>");
		out.println("Retrieving only calendars that a user owns");
		feedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
		resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
		out.println("<br>");
		out.println("Calendars you own:");
		System.out.println();
		boolean hasVocabulary = false;
		CalendarEntry choosedEntry = null;
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
		  CalendarEntry entry = resultFeed.getEntries().get(i);
		  out.println("<br>");
		  out.println("\t" + entry.getTitle().getPlainText());
		  
		  if(entry.getTitle().getPlainText().equals("VOA English Vocabulary")){
			  hasVocabulary = true;
			  choosedEntry = entry;
		  }
		  
		}
		
		if(hasVocabulary){
			  
		  }else{
			  CalendarEntry calendar = new CalendarEntry();
				calendar.setTitle(new PlainTextConstruct("VOA English Vocabulary"));
				calendar.setSummary(new PlainTextConstruct("This calendar contains the practice schedule and game times."));
				calendar.setTimeZone(new TimeZoneProperty("America/Los_Angeles"));
				calendar.setHidden(HiddenProperty.FALSE);
				calendar.setColor(new ColorProperty("#2952A3"));
				calendar.addLocation(new Where("","","Oakland"));

				// Insert the calendar
				URL postUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
				CalendarEntry returnedCalendar = myService.insert(postUrl, calendar);
				choosedEntry = returnedCalendar;
		  }
		  
		  if(choosedEntry != null){
			  out.println("<br>");
	    	  out.println("calendar choosedEntry.getId() :" + choosedEntry.getId());
	    	  
	    	  String id = choosedEntry.getId();
	    	  id = id.replaceAll("http://www.google.com/calendar/feeds/default/calendars/", "");
	    		//choosedEntry.
			  feedUrl = new URL("https://www.google.com/calendar/feeds/" + id + "/private/full");

				CalendarQuery myQuery = new CalendarQuery(feedUrl);
				Calendar calendar = Calendar.getInstance();
				Date now = calendar.getTime();
				
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				
				String todayString = dateFormat.format(now);
				
				myQuery.setMinimumStartTime(DateTime.parseDateTime(todayString + "T00:00:00"));
				myQuery.setMaximumStartTime(DateTime.parseDateTime(todayString + "T23:59:59"));

				// Send the request and receive the response:
				Feed resultFeed2 = myService.query(myQuery, Feed.class);

				boolean hasAdd = false;
		        for (int j = 0; j < resultFeed2.getEntries().size(); j++) {
		          Entry eventEntry = resultFeed2.getEntries().get(j);
		          
		          if(eventEntry.getTitle().getPlainText().toString().equals("google")){
		        	  hasAdd = true;
		          }
		          
		          //out.println("<br>");
		          //out.println(eventEntry.getTitle().getPlainText().toString());
		        }
		        
		        if(!hasAdd){

		    		//out.println("indicate : infopower.com.tw_enmv5k4v4hp7uhjomhhlbrk0jc@group.calendar.google.com");
		    		
		    		URL postUrl = new URL("https://www.google.com/calendar/feeds/" + id + "/private/full");
		        		CalendarEventEntry myEntry = new CalendarEventEntry();

		        		myEntry.setTitle(new PlainTextConstruct("google"));
		        		myEntry.setContent(new PlainTextConstruct("Meet for a quick lesson."));

		        		DateTime startTime = DateTime.parseDate(todayString);
		        		DateTime endTime = DateTime.parseDate(todayString);
		        		When eventTimes = new When();
		        		eventTimes.setStartTime(startTime);
		        		eventTimes.setEndTime(endTime);
		        		myEntry.addTime(eventTimes);

		        		// Send the request and receive the response:
		        		CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
		        		
		        		//choosedEntry.getService().insert(postUrl, myEntry);
		        		
		        }
		  }
		
		out.println("<br>");
		out.println("<br>");
		out.println("Retrieving events for a specified date range");
		feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");

		CalendarQuery myQuery = new CalendarQuery(feedUrl);
		myQuery.setMinimumStartTime(DateTime.parseDateTime("2011-05-16T00:00:00"));
		myQuery.setMaximumStartTime(DateTime.parseDateTime("2011-06-30T23:59:59"));

		// Send the request and receive the response:
		Feed resultFeed2 = myService.query(myQuery, Feed.class);

        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
          Entry entry = resultFeed2.getEntries().get(i);
          out.println("<br>");
          out.println(entry.getTitle().getPlainText().toString());
        }
		
		
		/*out.println("<br>");
		out.println("Creating new calendars");
		CalendarEntry calendar = new CalendarEntry();
		calendar.setTitle(new PlainTextConstruct("VOA English Vocabulary"));
		calendar.setSummary(new PlainTextConstruct("This calendar contains the practice schedule and game times."));
		calendar.setTimeZone(new TimeZoneProperty("America/Los_Angeles"));
		calendar.setHidden(HiddenProperty.TRUE);
		calendar.setColor(new ColorProperty("#2952A3"));
		calendar.addLocation(new Where("","","Oakland"));

		// Insert the calendar
		URL postUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
		CalendarEntry returnedCalendar = myService.insert(postUrl, calendar);
*/
/*		
out.println("<br>");out.println("<br>");
		//get user info
		
		String oauth_timestamp = OAuthUtil.getTimestamp();   //oauth要送出的參數資訊，可用google提供的OAuthUtil元件產生

		String oauth_nonce = OAuthUtil.getNonce();   //oauth要送出的參數資訊，可用google提供的OAuthUtil元件產生

		String oauth_token = accessToken;   //剛剛取得的access token

		String oauth_signature_method = "HMAC-SHA1";   //編碼方式

		String signature = null;   //準備用來存放簽名的字串

		String oauth_consumer_key = CONSUMER_KEY;

		Map<String, String> params = new HashMap();   
		//用來產生signature base string的參數

		params.put("oauth_consumer_key", oauth_consumer_key); 

		params.put("oauth_nonce", oauth_nonce); 

		params.put("oauth_signature_method", oauth_signature_method); 

		params.put("oauth_timestamp", oauth_timestamp); 

		params.put("oauth_token", oauth_token); 

		params.put("oauth_version", "1.0"); 

		String signatureBase = null;
		try {
			signatureBase = OAuthUtil.getSignatureBaseString("https://www.googleapis.com/userinfo/email", "GET", params);
		} catch (OAuthException e) {
			out.println(e.getMessage());
		}   //產生signature base string

		OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();   //編碼方法

		try {
			signature = signer.getSignature(signatureBase, oauthParameters);
		} catch (OAuthException e) {
			out.println(e.getMessage());
		}   //產生signature

		URL url = new URL("https://www.googleapis.com/userinfo/email");

		HttpURLConnection conn = (HttpURLConnection)url.openConnection();   //建立java HttpURLConnection物件...用來發送request

		conn.setRequestMethod("GET");

		conn.setRequestProperty("HOST","www.googleapis.com");

*/
		//conn.setRequestProperty("Accept","*/*");

		//送出的參數要經過url encode....可用OAuthUtil.encode完成
		/*

		conn.setRequestProperty("Authorization","OAuth oauth_version=\"1.0\", oauth_nonce=\""+OAuthUtil.encode(oauth_nonce)+"\", oauth_timestamp=\""+oauth_timestamp+"\", oauth_consumer_key=\""+OAuthUtil.encode(CONSUMER_KEY)+"\", oauth_token=\""+OAuthUtil.encode(oauth_token)+"\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\""+OAuthUtil.encode(signature)+"\"");

		conn.addRequestProperty("Content-Type","application/atom+xml");

		conn.connect();   //連接google送出request

		out.println("response code : "+conn.getResponseCode()+"<br/>");   //如果正確的話應該傳回200，若為401則表示送出的authorization資訊有誤

		out.println("response message : "+conn.getResponseMessage()+"<br/>");   //正確的話是OK

		//接取google傳回的使用者資訊

		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

		String tmp = "", result = "";

		while((tmp=reader.readLine())!=null){

			result += tmp;

		}	

		out.println("insertResult = "+result);   //如果正確的話會傳回email=userXXX@gmail.com&isVerified=true

		reader.close();
*/
		
%>
<script>
window.opener.location.reload();
window.close();
</script>
</body>
</html>